<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑数据同步任务' : '新增数据同步任务'"
    width="80%"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 基本信息 -->
      <BasicInfo 
        :form="form"
        :data-source-options="dataSourceOptions"
        :table-options="tableOptions"
        @update:tableOptions="updateTableOptions"
        @fetch-columns="fetchColumnsHandler"
        @reset-columns="resetColumnsHandler"
      />

      <!-- 目标字段配置 -->
      <TargetColumns 
        :form="form" 
        :column-options="columnOptions" 
      />

      <!-- 目源关系配置 -->
      <SourceMapping 
        :form="form" 
        :data-source-options="dataSourceOptions" 
        :source-table-columns="sourceTableColumns"
        @fetch-source-columns="fetchSourceColumnsHandler" 
      />
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { getDataSourceList, createTask, updateTask } from '@/api/data-sync';
import { defaultFormValues, formRules, fetchColumns } from './form-utils';
import BasicInfo from './form-sections/BasicInfo.vue';
import TargetColumns from './form-sections/TargetColumns.vue';
import SourceMapping from './form-sections/SourceMapping.vue';

// 定义Props和Emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:visible', 'success']);

// 对话框可见状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emits('update:visible', val)
});

// 表单引用
const formRef = ref();
const loading = ref(false);
const submitLoading = ref(false);

// 表单数据
const form = reactive<any>({ ...defaultFormValues });

// 表单校验规则
const rules = formRules;

// 数据源选项
const dataSourceOptions = ref<any[]>([]);
// 表名选项
const tableOptions = ref<string[]>([]);
// 列名选项
const columnOptions = ref<string[]>([]);
// 源表列名映射 (db_id:table_name -> columns[])
const sourceTableColumns = ref<Record<string, string[]>>({});

// 重置表单
const resetForm = () => {
  // 重置所有表单字段为默认值
  Object.keys(defaultFormValues).forEach(key => {
    if (Array.isArray(defaultFormValues[key])) {
      form[key] = [];
    } else {
      form[key] = defaultFormValues[key];
    }
  });
  
  // 清空其他相关状态
  columnOptions.value = [];
  tableOptions.value = [];
  sourceTableColumns.value = {};
  
  // 重置表单校验状态
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 初始化
const init = async () => {
  loading.value = true;
  try {
    // 获取数据源选项
    await fetchDataSources();
    
    // 如果是编辑模式，初始化表单数据
    if (props.isEdit && props.formData) {
      // 使用深拷贝避免修改原始数据
      const data = JSON.parse(JSON.stringify(props.formData));
      Object.keys(form).forEach(key => {
        if (data[key] !== undefined) {
          form[key] = data[key];
        }
      });
      
      // 如果有数据源和表名，加载表名列表和列名列表
      if (form.db_info_setting_id) {
        if (form.table_name) {
          await fetchColumnsHandler(form.db_info_setting_id, form.table_name);
        }
      }
      
      // 加载源表的列信息
      await Promise.all(form.ts_mapping.map(async (mapping: any) => {
        if (mapping.db_info_setting_id && mapping.source_table_name) {
          await fetchSourceColumnsHandler(mapping.db_info_setting_id, mapping.source_table_name);
        }
      }));
    }
  } catch (error) {
    console.error('初始化表单失败:', error);
    ElMessage.error('初始化表单失败');
  } finally {
    loading.value = false;
  }
};

// 获取数据源列表
const fetchDataSources = async () => {
  try {
    const res: any = await getDataSourceList();
    if (res.code === 200 && res.data) {
      dataSourceOptions.value = res.data;
    }
  } catch (error) {
    console.error('获取数据源列表失败:', error);
    ElMessage.error('获取数据源列表失败');
  }
};

// 更新表名选项
const updateTableOptions = (tables: string[]) => {
  tableOptions.value = tables;
};

// 获取列名列表处理函数
const fetchColumnsHandler = async (dbId: string, tableName: string) => {
  const columns = await fetchColumns(dbId, tableName);
  columnOptions.value = columns;
  return columns;
};

// 重置列名列表处理函数
const resetColumnsHandler = () => {
  form.details = [];
  columnOptions.value = [];
};

// 获取源表列名列表处理函数
const fetchSourceColumnsHandler = async (dbId: string, tableName: string) => {
  if (!dbId || !tableName) return;
  
  const key = `${dbId}:${tableName}`;
  
  // 如果已经获取过，直接返回
  if (sourceTableColumns.value[key]) {
    return;
  }
  
  const columns = await fetchColumns(dbId, tableName);
  sourceTableColumns.value[key] = columns;
};

// 表单验证函数
const validateForm = () => {
  if (!form.details.length) {
    ElMessage.warning('请添加至少一个目标列');
    return false;
  }

  // 校验目标列是否都选择了列名
  const invalidDetails = form.details.some((item: any) => !item.column_name);
  if (invalidDetails) {
    ElMessage.warning('目标列中有未选择列名的项');
    return false;
  }

  // 校验目源关系映射
  for (const mapping of form.ts_mapping) {
    if (!mapping.target_column_name) {
      ElMessage.warning('目源关系中有未选择目标列名的项');
      return false;
    }
    
    if (!mapping.db_info_setting_id) {
      ElMessage.warning('目源关系中有未选择来源数据源的项');
      return false;
    }
    
    if (!mapping.source_table_name) {
      ElMessage.warning('目源关系中有未选择来源表名的项');
      return false;
    }
    
    if (!mapping.source_column_name) {
      ElMessage.warning('目源关系中有未选择来源列名的项');
      return false;
    }
    
    // 校验目标列名是否存在于目标列中
    const targetColumnExists = form.details.some(
      (item: any) => item.column_name === mapping.target_column_name
    );
    
    if (!targetColumnExists) {
      ElMessage.warning(`目源关系中的目标列名 ${mapping.target_column_name} 不在目标列中`);
      return false;
    }
  }

  return true;
};

// 提交表单
const submitForm = async () => {
  // 自定义验证
  if (!validateForm()) {
    return;
  }
  
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      const formData = {
        task_name: form.task_name,
        db_info_setting_id: form.db_info_setting_id,
        table_name: form.table_name,
        query_condition: form.query_condition,
        data_limit: form.data_limit,
        cron_expression: form.cron_expression,
        status: form.status,
        details: form.details,
        ts_mapping: form.ts_mapping
      };
      
      let res: any;
      
      if (props.isEdit) {
        // 编辑模式
        res = await updateTask(props.formData._id, formData);
      } else {
        // 新增模式
        res = await createTask(formData);
      }
      
      if (res.code === 200) {
        ElMessage.success(props.isEdit ? '编辑成功' : '新增成功');
        emits('success');
      } else {
        ElMessage.error(res.message || (props.isEdit ? '编辑失败' : '新增失败'));
      }
    } catch (error) {
      console.error(props.isEdit ? '编辑失败:' : '新增失败:', error);
      ElMessage.error(props.isEdit ? '编辑失败' : '新增失败');
    } finally {
      submitLoading.value = false;
    }
  });
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  // 在关闭时也重置表单
  resetForm();
};

// 监听visible变化，初始化表单
watch(() => props.visible, (val) => {
  if (val) {
    // 重置表单，确保每次打开表单时都是干净的状态
    resetForm();
    // 然后根据编辑状态初始化
    nextTick(() => {
      init();
    });
  }
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>